package cn.player.act;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;

import org.json.JSONObject;

import java.util.List;

import cn.player.R;
import cn.player.act.frag.ChannelInfoFragment;
import cn.player.act.frag.RecomInfoFragment;
import cn.player.act.frag.SelectInfoFragment;
import cn.player.adapter.RightRecomInfoAdapter;
import cn.player.entity.RecomInfo;
import cntv.player.core.util.ToastUtil;
import cntv.player.engine.Const;
import cn.player.media.entity.VideoInfo;
import cn.player.media.fragment.MediaPlayFragment;

/**
 * 可横屏可竖屏
 *
 * @author zengliang
 */
public class MediaPlayActivity extends BaseActivity {

    private VideoInfo videoInfo;
    private MediaPlayFragment mpFrag;
    private String channelId;
    private String channelUrl;
    private String epgUrl;
    private String recomUrl;
    private List<RecomInfo> mRecomInfos;
    public RightRecomInfoAdapter mRecomInfoAdapter;

    private boolean isLiveFlag;

    //	private RecomInfoFragment mRecomFrag;
    private LinearLayout llChannel;
    private Button btnClickToPlay;
    private OnClickListener mOnClickListener;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.media_play_layout);

        Log.i("zl", "MediaPlayActivity onCreate");

        videoInfo = (VideoInfo) getIntent().getSerializableExtra(VideoInfo.class.getName());
        if (videoInfo == null) {
            playError(0, "MediaPlayActivity get VideoInfo null...");
            return;
        }

        isLiveFlag = (videoInfo.getFlag() == Const.LIVE);

        findViews();
        setListener();

        getPlayInfo();

        addPlayer();

    }

    private void removePlayer() {
        if (mpFrag != null && mpFrag.isAdded()) {
            FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
            ft.remove(mpFrag);
            ft.commit();
        }
    }

    /**
     * 添加播放器
     */
    private void addPlayer() {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        if (mpFrag == null) {
            mpFrag = MediaPlayFragment.newInstance(videoInfo);
        }
        if (mpFrag.isAdded()) {
            ToastUtil.showToast(mContext, "您已经添加播放器了....", Toast.LENGTH_SHORT);
            return;
        }

        ft.add(R.id.ll_play_area, mpFrag); // 在id为ll_play_area的LinearLayout布局中显示mpFrag
        ft.commit();
        mpFrag.setOnPlayerListener(new MediaPlayFragment.OnPlayerListener() {

            @Override
            public void onPlayStart() {
                // TODO Auto-generated method stub

            }

            @Override
            public void onPlayPauseChanged(boolean isPaused) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onPlayError(int errorNo, String errMsg) {
                // TODO Auto-generated method stub
                Log.i("zl", "mediaplayActivity onPlayError,errorNo = " + errorNo + ",errMsg = " + errMsg);
                removePlayer();
                playError(errorNo, errMsg);
            }

            @Override
            public void onPlayComplete() {
                // TODO Auto-generated method stub

            }

        });


        addRecomFrag();
        if (isLiveFlag) {
            addChanFrag();
        } else {
            addSelectEpiFrag();
            addSelectBestFrag();
        }
    }

    /**
     * 添加全屏推荐列表
     */
    private void addRecomFrag() {
        RecomInfoFragment mRecomFrag = RecomInfoFragment.newInstance(recomUrl);
        mpFrag.addRightInfo(MediaPlayFragment.TAB_RECOM, mRecomFrag);
    }

    /**
     * 添加全屏频道列表
     */
    private void addChanFrag() {
        ChannelInfoFragment mChanFrag = ChannelInfoFragment.newInstance(channelUrl);
        mpFrag.addRightInfo(MediaPlayFragment.TAB_CHAN, mChanFrag);
    }

    /**
     * 添加全屏选集列表
     */
    private void addSelectEpiFrag() {
        SelectInfoFragment mSelectFrag = SelectInfoFragment.newInstance("C40858", MediaPlayFragment.TAB_EPI);
//		SelectInfoFragment mSelectFrag = SelectInfoFragment.newInstance("VSET100187618898",MediaPlayFragment.TAB_EPI);
        mpFrag.addRightInfo(MediaPlayFragment.TAB_EPI, mSelectFrag);
    }

    /**
     * 添加全屏精集列表
     */
    private void addSelectBestFrag() {
        SelectInfoFragment mSelectFrag = SelectInfoFragment.newInstance("C40858", MediaPlayFragment.TAB_BEST);
//		SelectInfoFragment mSelectFrag = SelectInfoFragment.newInstance("VSET100187618898",MediaPlayFragment.TAB_BEST);
        mpFrag.addRightInfo(MediaPlayFragment.TAB_BEST, mSelectFrag);
    }


    private void getPlayInfo() {
        // TODO Auto-generated method stub
        channelId = videoInfo.getChannelId();
        if (channelId == null) {
            channelId = "cctv6";
        }

//		channelUrl = videoInfo.getChannelUrl();

        channelUrl = getIntent().getStringExtra("categoryUrl");
        if (channelUrl == null) {
            channelUrl = "http://serv.cbox.cntv.cn/json/zhibo/yangshipindao/ysmc/index.json";
        }

        recomUrl = app.getBaseUrls().get(Const.KEY_RECOM_URL).getUrl() + "&p=1&n=100&channel=" + channelId;
        epgUrl = app.getBaseUrls().get(Const.KEY_EPG_URL).getUrl() + "?&d=0&c=" + channelId;

    }

    @Override
    protected void initDataSuccess(String url, JSONObject response) {
        // TODO Auto-generated method stub
        super.initDataSuccess(url, response);
        try {
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }

    private void findViews() {
        // TODO Auto-generated method stub
        llChannel = (LinearLayout) findViewById(R.id.ll_channel_area_test);
        btnClickToPlay = (Button) findViewById(R.id.btn_click_to_play);
    }

    private void setListener() {
        // TODO Auto-generated method stub
        mOnClickListener = new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                switch (v.getId()) {
                    case R.id.btn_click_to_play:
                        addPlayer();
                        break;

                    default:
                        break;
                }
            }
        };
        btnClickToPlay.setOnClickListener(mOnClickListener);
    }


    /**
     * 弹框提示播放错误
     */
    private void playError(int errNo, String errMsg) {
        // TODO Auto-generated method stub
        new AlertDialog.Builder(this).setTitle("提示").setMessage(errMsg)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // TODO Auto-generated method stub
                        dialog.dismiss();
//				finish();
                    }
                }).show();
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub

        //如果播放器只有横屏，不用重写此方法
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            if (mpFrag != null && !mpFrag.isPortraitScreen()) {
                mpFrag.setPortrait();
                return true;
            }
        }
        if (mpFrag != null) {
            mpFrag.onKeyDownVolume(keyCode, event);
        }
        return super.onKeyDown(keyCode, event);

    }

	
	
	
/*		@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		Log.i("zl","MediaPlayActivity onStart");
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		Log.i("zl","MediaPlayActivity onResume");
	}
	
	
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		Log.i("zl","MediaPlayActivity onPause");
	}
	
	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		Log.i("zl","MediaPlayActivity onStop");
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		Log.i("zl","MediaPlayActivity onDestroy");
	}*/


}
